#include "cat-client.hpp"
#include <winsock.h>

CatClient::CatClient()
{
}

CatClient::~CatClient()
{
}

void CatClient::SetClientPort(int _port)
{
	port = _port;
}

bool CatClient::SendData(int action, char* data, unsigned int size)
{

	if (socket.connect("127.0.0.1", port,sf::milliseconds(100)) == sf::Socket::Done) {
		SendSocketDataAsync(0, 0, action, data, size);
		return true;
	}
	return false;
}

void CatClient::SendSocketDataAsync(int packetlength, short ver, int action, const char* body, unsigned int size)
{
	if (packetlength == 0) {
		packetlength = size + 12;
	}

	char* ptr;
	char* header = new char[12];

	uint32_t pack_len = 12 + size,
		header_len = htons(12),
		proto_version = htons(ver),
		_action = htonl(action),
		pack_len_converted = htonl(pack_len);

	memcpy(&header[0], &pack_len_converted, 4);
	memcpy(&header[4], &header_len, 2);
	memcpy(&header[6], &proto_version, 2);
	memcpy(&header[8], &_action, 4);

	if (size > 0) {
		ptr = new char[packetlength];
		memcpy(ptr, header, 12);
		memcpy(ptr + 12, body, size);
	}
	else
	{
		ptr = (char*)malloc(12);
		memcpy(ptr, header, 12);
	}
	
	socket.send(ptr, packetlength);
	delete ptr, header;
}

void CatClient::ProcessData(int action, char* buffer, int size)
{
}

void CatClient::PrintMessage(std::string message)
{
}

void CatClient::_disconnect()
{
}
